﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using OurSite.Business;
using OurSite.Business.Helper;
using OurSite.Business.Repositories;
using OurSite.WebAdmin.Models;

namespace OurSite.WebAdmin.Controllers
{

    [HandleError]
    public class AccountController : BaseController
    {
        #region Protected Properties
        IUserRepository userRepository = new UserRepository();
        #endregion

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            User user = userRepository.GetByUserName(model.UserName, model.Password);
            string message = "The username or password you entered is incorrect.";

            if (user != null)
            {
                string allRoles = string.Empty;
                if (user.Roles != null)
                {
                    foreach (Role role in user.Roles)
                        allRoles += "|" + role.RoleName;
                }
                allRoles = allRoles.EndsWith("|") ? allRoles.Remove(allRoles.Length - 1, 1) : allRoles;

                if (allRoles.IndexOf("ADMIN") >= 0)
                {
                    Session["CurrentUser"] = user;

                    FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, allRoles);

                    string encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket);

                    HttpCookie formAuthenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                    Response.Cookies.Add(formAuthenticationCookie);
                    message = "success";
                }
            }

            AEFacebook facebook = new AEFacebook();
            if (!string.IsNullOrEmpty(returnUrl))
                facebook.CallBackUrl = ConvertRelativeUrlToAbsoluteUrl(returnUrl);
            else
                facebook.CallBackUrl = Request.Url.AbsoluteUri;

            return Redirect(facebook.AuthorizationLinkGet());


        }

        public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl)
        {
            
            if (Request.IsSecureConnection)
                return string.Format("https://{0}{1}", Request.Url.Authority, Url.Content(relativeUrl));

            return string.Format("http://{0}{1}", Request.Url.Authority, Url.Content(relativeUrl));
        }

    }
}
